const express = require('express');
const router = express.Router();
const { User } = require('../../models')
const { Op } = require('sequelize')
const { success, failure } = require('../../utils/responses');
const { NotFoundError, BadRequestError, UnauthorizedError } = require('../../utils/errors')
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
// const crypto = require('crypto');

//管理员登录
router.post('/sign_in', async (req, res) => {
    try {
        //生成一个随机数，放到token的env文件中使用
        // console.log(crypto.randomBytes(32).toString('hex'));
        
        const { login, password } = req.body;
        if (!login) {
            throw new BadRequestError('邮箱或用户名不能为空')
        }
        if (!password) {
            throw new BadRequestError("密码不能为空");

        }

        //查询数据库是否有该用户
        const condition = {
            where: {
                [Op.or]: [
                    { email: login },
                    { username: login }
                ]
            }
        }
        const user = await User.findOne(condition)
        if (!user) {
            throw new NotFoundError('用户不存在,无法登陆')
        }

        //验证密码是否正确
        const isPasswordValid = bcrypt.compareSync(password, user.password)
        if (!isPasswordValid) {
            throw new UnauthorizedError('密码错误')
        }

        //验证是否是管理员
        if (user.role !== 100) {
            throw new UnauthorizedError('您没有权限登录管理员后台')
        }

        //生成token
        const token = jwt.sign({
            userId: user.id,
        }, process.env.SECRET, { expiresIn: '30d' })

        success(res, '登录成功', {token})
    } catch (error) {
        failure(res, error)
    }

})

module.exports = router;